#include "vbb_SPI.h"

void vbb_SPI_Init(VBB_SPI * Spi, SPI_TypeDef * SPIx)
{
    if (SPIx == SPI1)
    {
        Spi->SPIx = SPIx;
        
        RCC->APB2ENR |= RCC_APB2ENR_AFIOEN;
        RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
        AFIO->MAPR &= ~AFIO_MAPR_SPI1_REMAP;
        AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE;                
        
        vbb_PIN_Init(&(Spi->pin_clk), GPIOA, 5, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
        vbb_PIN_Init(&(Spi->pin_miso), GPIOA, 6, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
        vbb_PIN_Init(&(Spi->pin_mosi), GPIOA, 7, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
        
        SPIx->CR1 = (SPI_CR1_SSM | SPI_CR1_SSI | SPI_CR1_BR | SPI_CR1_MSTR);
        SPIx->I2SCFGR &= ~SPI_I2SCFGR_I2SMOD;
        SPIx->CRCPR = 0x0007;
        SPIx->CR1 |= SPI_CR1_SPE;
    }
    else if (SPIx == SPI3)
    {
        Spi->SPIx = SPIx;
        
        if (!(SPIx->CR1 & SPI_CR1_SPE))
        {
            RCC->APB2ENR |= RCC_APB2ENR_AFIOEN;        
            RCC->APB1ENR |= RCC_APB1ENR_SPI3EN;
            AFIO->MAPR &= ~AFIO_MAPR_SPI1_REMAP;
            AFIO->MAPR |= AFIO_MAPR_SWJ_CFG_JTAGDISABLE; 
            
            vbb_PIN_Init(&(Spi->pin_clk), GPIOB, 3, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
            vbb_PIN_Init(&(Spi->pin_miso), GPIOB, 4, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
            vbb_PIN_Init(&(Spi->pin_mosi), GPIOB, 5, PIN_MODE_ALTERNATE_OUTPUT_PUSH_PULL);
            
            SPIx->CR1 = (SPI_CR1_SSM | SPI_CR1_SSI | SPI_CR1_BR | SPI_CR1_MSTR);
            SPIx->I2SCFGR &= ~SPI_I2SCFGR_I2SMOD;
            SPIx->CRCPR = 0x0007;
            SPIx->CR1 |= SPI_CR1_SPE;
        }
    }
}

char vbb_SPI_WriteByte(VBB_SPI * Spi, char Byte)
{
    while (!(Spi->SPIx->SR & SPI_SR_TXE)) {}              
    Spi->SPIx->DR = Byte;    
    while (!(Spi->SPIx->SR & SPI_SR_RXNE)) {}    
    return Spi->SPIx->DR;
}
